package com.pshcp.api;

import com.alibaba.fastjson.JSONObject;
import com.external.hospital.base.BaseRes;
import com.framework.base.ResultDTO;
import com.framework.thread.ReqComTool;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2023/3/17 16:21
 */

@ControllerAdvice
public class ResponseBodyAdviceAPI implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //添加请求时间和返回时间，计算接口总耗时
        if(body instanceof BaseRes){
            ((BaseRes) body).setTraceId(ReqComTool.getPshcpTraceId());
            return body;
        }
        if(body instanceof ResultDTO){
            ((ResultDTO) body).setTraceId(ReqComTool.getPshcpTraceId());
            return body;
        }
        if(body instanceof JSONObject){
            ((JSONObject) body).put("traceId",ReqComTool.getPshcpTraceId());
            return body;
        }
        return body;
    }
}
